package com.example.NearByLocation;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.*;
import com.baidu.navisdk.BNaviEngineManager;
import com.baidu.navisdk.BNaviPoint;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams;

/**
 * Created by Administrator on 2014/11/30.
 */
public class RouteLineActivity extends Activity {
    private Button toMap_bt;
    private String name;
    private String address;
    private String distance;
    private String phoneNum;
    private LatLng mLatlng;
    private LatLng tolatLng;
    private String mName;
    private TextView routeLong_text;
    private TextView route_name_text;
    private TextView route_address_text;
    private String longi1;
    private String leni1;
    private Button phone_bt;
    private Button route_guide_bt;
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    boolean isFirstLoc = true;
    int nodeIndex = -1;//节点索引,供浏览节点时使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = true;
    private TextView popupText = null;//泡泡view

    //地图相关，使用继承MapView的MyRouteMapView目的是重写touch事件实现泡泡处理
    //如果不处理touch事件，则无需继承，直接使用MapView即可
    MapView mMapView = null;    // 地图View
    BaiduMap mBaidumap = null;
    //搜索相关
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    private boolean mIsEngineInitSuccess = false;
    private BNaviEngineManager.NaviEngineInitListener mNaviEngineInitListener = new BNaviEngineManager.NaviEngineInitListener() {
        public void engineInitSuccess() {
            //导航初始化是异步的，需要一小段时间，以这个标志来识别引擎是否初始化成功，为true时候才能发起导航
            mIsEngineInitSuccess = true;
        }

        public void engineInitStart() {
        }

        public void engineInitFail() {
        }
    };

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(
                Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.routeline);


        BaiduNaviManager.getInstance().
                initEngine(this, getSdcardDir(), mNaviEngineInitListener, "fD8aCYbCZjqgcm53Fz6nHGIG", null);
        //取按键
        toMap_bt = (Button) findViewById(R.id.toMap_bt);
        mMapView = (MapView) findViewById(R.id.map);
        routeLong_text = (TextView) findViewById(R.id.routeLong_text);
        route_name_text = (TextView) findViewById(R.id.route_name_text);
        route_address_text = (TextView) findViewById(R.id.route_address_text);
        phone_bt = (Button) findViewById(R.id.phone_bt);
        route_guide_bt = (Button) findViewById(R.id.route_guide_bt);
        mBaidumap = mMapView.getMap();
        mSearch = RoutePlanSearch.newInstance();


//取数据
        toMap_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        final Intent intent = getIntent();
        name = intent.getStringExtra("name");
        address = intent.getStringExtra("address");
        distance = intent.getStringExtra("distance");
        phoneNum = intent.getStringExtra("phoneNum");
        longi1 = intent.getStringExtra("longi1");
        leni1 = intent.getStringExtra("leni1");
        tolatLng = new LatLng(Double.parseDouble(leni1), Double.parseDouble(longi1));
        LocationManager locationManager = new LocationManager();
        mLatlng = locationManager.getAdd();
        mName = locationManager.getAddName();
//初始化
        String distanceStr = changeDis(distance);
        routeLong_text.setText("全程约" + distanceStr + "公里");
        route_name_text.setText(name);
        route_address_text.setText(address);
 //电话信息
       if (phoneNum.equals("")) {
            phone_bt.setText("暂无电话信息");
        } else {
            phone_bt.setText(phoneNum);
            phone_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent1=new Intent(Intent.ACTION_DIAL);
                    intent1.setData(Uri.parse("tel:"+phoneNum));
                    startActivity(intent1);
                }
            });
        }
        init();
        //导航
        route_guide_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routeGuide();
            }
        });
        //地图点击事件处理
        mBaidumap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaidumap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        mSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    getCurrentLoc();
                    Toast.makeText(RouteLineActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    WalkingRouteOverlay overlay = new MyWalkingRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    getCurrentLoc();
                    Toast.makeText(RouteLineActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    TransitRouteOverlay overlay = new MyTransitRouteOverlay(mBaidumap);
                    mBaidumap.setOnMarkerClickListener(overlay);
                    routeOverlay = overlay;
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    getCurrentLoc();
                    Toast.makeText(RouteLineActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                    //result.getSuggestAddrInfo()
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    nodeIndex = -1;
                    route = result.getRouteLines().get(0);
                    DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaidumap);
                    routeOverlay = overlay;
                    mBaidumap.setOnMarkerClickListener(overlay);
                    overlay.setData(result.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }
        });
    }

    private void routeGuide() {
        //这里给出一个起终点示例，实际应用中可以通过POI检索、外部POI来源等方式获取起终点坐标
        String cName = mName;
        for (int i = 0; i < cName.length(); i++) {
            if (cName.charAt(i) == '区' || cName.charAt(i) == '县') {
                cName = cName.substring(i + 1, cName.length());
            }
        }
        Log.d("cName", cName);

        BNaviPoint startPoint = new BNaviPoint(mLatlng.longitude, mLatlng.latitude,
                cName, BNaviPoint.CoordinateType.BD09_MC);
        BNaviPoint endPoint = new BNaviPoint(tolatLng.longitude, tolatLng.latitude,
                name, BNaviPoint.CoordinateType.BD09_MC);
        BaiduNaviManager.getInstance().launchNavigator(this,
                startPoint,                                      //起点（可指定坐标系）
                endPoint,                                        //终点（可指定坐标系）
                RoutePlanParams.NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME,       //算路方式
                true,                                            //真实导航
                BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, //在离线策略
                new BaiduNaviManager.OnStartNavigationListener() {                //跳转监听

                    @Override
                    public void onJumpToNavigator(Bundle configParams) {
                        Intent intent = new Intent(RouteLineActivity.this, BNavigatorActivity.class);
                        intent.putExtras(configParams);
                        startActivity(intent);
                    }

                    @Override
                    public void onJumpToDownloader() {
                    }
                });
    }

    private String changeDis(String distence) {
        int dist = Integer.parseInt(distence);
        String sum = "0";
        int qian = 0;
        if (dist % 1000 == 0) {
            qian = dist / 1000;
            sum = String.valueOf(qian);
            return sum;
        } else {
            String q = String.valueOf(dist / 1000);
            String bai = String.valueOf((dist - (dist / 1000) * 1000) / 100);
            int a = dist - (dist / 1000) * 1000;
            int shi = (a - (a / 100) * 100) / 10;
            if (shi >= 5) {
                sum = q + "." + String.valueOf(a / 100 + 1);
            }
            if (shi < 5) {
                sum = q + "." + bai;
            }

            return sum;
        }
    }

    private void init() {
        if (tolatLng == null || mLatlng == null) {
            Toast.makeText(RouteLineActivity.this, "没有获取位置信息", Toast.LENGTH_SHORT).show();
        } else {
            //重置浏览节点的路线数据
            route = null;
            mBaidumap.clear();
            //设置起终点信息，对于tranist search 来说，城市名无意义
//            PlanNode stNode = PlanNode.withCityNameAndPlaceName("西安", "科技二路68号");
//            PlanNode enNode = PlanNode.withCityNameAndPlaceName("西安", name);
            PlanNode stNode = PlanNode.withLocation(mLatlng);
            PlanNode enNode = PlanNode.withLocation(tolatLng);
            // 实际使用中请对起点终点城市进行正确的设定

            mSearch.walkingSearch((new WalkingRoutePlanOption())
                    .from(stNode)
                    .to(enNode));

        }

    }

    public void SearchButtonProcess(View v) {
        if (tolatLng == null || mLatlng == null) {
            Toast.makeText(RouteLineActivity.this, "没有获取当前位置", Toast.LENGTH_SHORT).show();
        } else {
            //重置浏览节点的路线数据
            route = null;
            mBaidumap.clear();
            //设置起终点信息，对于tranist search 来说，城市名无意义
//           PlanNode stNode = PlanNode.withCityNameAndPlaceName("西安", mAddress);
//           PlanNode enNode = PlanNode.withCityNameAndPlaceName("西安", name);
            PlanNode stNode = PlanNode.withLocation(mLatlng);
            PlanNode enNode = PlanNode.withLocation(tolatLng);
            // 实际使用中请对起点终点城市进行正确的设定
            String cityName = mName;
            for (int i = 0; i < cityName.length(); i++) {
                if (cityName.charAt(i) == '省') {
                    cityName = cityName.substring(i + 1, cityName.length());
                    for (int j = 0; j < cityName.length(); j++) {
                        if (cityName.charAt(j) == '市') {
                            cityName = cityName.substring(0, j);
                            break;
                        }
                    }
                }

            }
            if (v.getId() == R.id.bycar_bt) {
                mSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            } else if (v.getId() == R.id.bus_bt) {
                mSearch.transitSearch((new TransitRoutePlanOption())
                        .from(stNode)
                        .city(cityName)
                        .to(enNode));
                Log.d("cityName", cityName);
            } else if (v.getId() == R.id.onfoot_bt) {
                mSearch.walkingSearch((new WalkingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            }
        }

    }

    //定制RouteOverly
    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {

        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    private class MyWalkingRouteOverlay extends WalkingRouteOverlay {

        public MyWalkingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    private class MyTransitRouteOverlay extends TransitRouteOverlay {

        public MyTransitRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_from);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_to);
            }
            return null;
        }
    }

    private void getCurrentLoc() {
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mCurrentMarker = null;
        mBaidumap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));

        mBaidumap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mBaidumap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaidumap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

}
